package com.bims.jreport.exception.handler;

import com.bims.jreport.controller.RestResult;
import com.bims.jreport.exception.GenerateTempException;
import com.bims.jreport.utils.I18nMessagesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

import static com.bims.jreport.constant.ReportErrorCodeConstant.*;
import static java.util.stream.Collectors.toList;

@Slf4j
@RestControllerAdvice
public class RestExceptionHandler {

    @Autowired
    I18nMessagesUtil messagesUtil;

    @ExceptionHandler(value = GenerateTempException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestResult generateExceptionHandler() {
        return messagesUtil.getFailedResponse(COMMON_GENERATE_ERROR);
    }


    /**
     * 参数不匹配异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public RestResult handleException(MissingServletRequestParameterException e) {
        return messagesUtil.getFailedResponse(COMMON_REQUEST_MISSING_PARAM, new Object[]{e.getParameterName()});
    }

    /**
     * 处理校验异常
     * 
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public RestResult handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        List<String> errorMessages = ex.getBindingResult()
                .getAllErrors().stream().map(e -> messagesUtil.getMessage(e.getDefaultMessage())).collect(toList());

        return RestResult.newFailedInstance(COMMON_REQUEST_ARGUMENT_NOT_VALID,
                messagesUtil.getMessage(COMMON_REQUEST_ARGUMENT_NOT_VALID), errorMessages);
    }


}
